package com.javid.study.controller;

import com.javid.study.common.MyWebsocket;
import com.javid.study.common.Result;
import com.javid.study.pojo.NynInfo;
import com.javid.study.pojo.NynPoker;
import com.javid.study.service.InfoService;
import com.javid.study.service.InitService;
import com.javid.study.service.PokerService;
import com.javid.study.vo.*;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@RestController
@RequestMapping("/api")
public class NYNController {
    @Autowired
    private InitService initService;
    @Autowired
    private PokerService pokerService;
    @Autowired
    private InfoService infoService;
    @Autowired
    private Result result;
    @Autowired
    private InfoData infoData;
    @Autowired
    private MyWebsocket myWebsocket;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    //    String[] pokerColor = {"♠", "♥", "♣", "♦"};
    enum pokerColor {
        HEITAO(1, "♠"),
        HONGXIN(2, "♥"),
        MEIHUA(3, "♣"),
        FANGPIAN(4, "♦");

        pokerColor(int id, String name) {
        }
    }

    private String[] savePoker = {"A", "2", "5", "8", "10"};

    @PostMapping("/init")
    public Result init(Init init) {
        if (!init.getNameList().contains("，")) {
            return result.error("人名请使用中文逗号分隔");
        }
        if (!initService.init(init.getNameList())) {
            return result.error("人数应在2-9个，无法开局");
        }
        return result.success();
    }

    @GetMapping("/onemore")
    public Result onemore() {
        initService.onemore();
        myWebsocket.sendMessageToAllUser();
        return result.success();
    }

    @GetMapping("/getInfo")
    public Result getInfo() {
        int count = infoService.getInfoCount();
        if (count == 0) {
            return result.error("还未开局，请先完成初始化！");
        }
        infoData.setCount(count);
        InfoListData[] infoList = new InfoListData[count];
        for (NynInfo nynInfo : infoService.getAllInfo()) {
            InfoListData infoListData = new InfoListData();
            infoListData.setNumber(nynInfo.getPlayerid());
            infoListData.setName(nynInfo.getName());
            List<String> listPoker = new ArrayList<>();
            for (NynPoker poker : pokerService.selectByPlayerid(nynInfo.getPlayerid())) {
                if (Arrays.stream(savePoker).anyMatch(k -> k.equals(poker.getName().substring(1)))) {
                    listPoker.add(poker.getName());
                }
            }
            infoListData.setPokerList(listPoker);
            infoListData.setHasDrinkedNum(nynInfo.getHasdrinked());
            infoListData.setNeedDrinkNum(nynInfo.getNeeddrink());
            infoList[nynInfo.getPlayerid() - 1] = infoListData;
        }
        infoData.setInfoList(infoList);
        String n = redisTemplate.opsForValue().get("now");
        if (!StringUtils.isEmpty(n)) {
            infoData.setNow(Integer.parseInt(n));
        }
        infoData.setPresentPokerNum(pokerService.getPokerCount());
        String i = redisTemplate.opsForValue().get("whohas2");
        if (!StringUtils.isEmpty(i)) {
            int sisterid = Integer.parseInt(i);
            infoData.setSister(sisterid);
        }
        String p = redisTemplate.opsForValue().get("lastpoker");
        if (!StringUtils.isEmpty(p)) {
            infoData.setLastgetPoker(p);
            infoData.setPokerDesc(pokerService.getRule(p).getRule());
        }
        return result.success(infoData);
    }

    @GetMapping("/isDrink")
    public Result isDrink(isDrink isdrink) {
        int count = infoService.getInfoCount();
        int playerNum = isdrink.getPlayerNum();
        if (count == 0) {
            return result.error("还未开局，请先完成初始化！");
        }
        if (playerNum > count || playerNum < 1) {
            return result.error("PlayerNum参数错误");
        }
        NynInfo info = new NynInfo();
        if (isdrink.getSelect() == 1) {
            info.setHasdrinked(infoService.getOne(NynInfo::getPlayerid, playerNum).getHasdrinked() + 1);
            infoService.updateInfo(playerNum, info);
        } else if (isdrink.getSelect() == 0) {
            info.setNeeddrink(infoService.getOne(NynInfo::getPlayerid, playerNum).getNeeddrink() + 1);
            infoService.updateInfo(playerNum, info);
        } else {
            return result.error("传参错误");
        }
        myWebsocket.sendMessageToAllUser();
        return result.success();
    }

    @PostMapping("/usePoker")
    public Result usePoker(usePoker usepoker) {
        int count = infoService.getInfoCount();
        if (count == 0) {
            return result.error("还未开局，请先完成初始化！");
        }
        String poker = usepoker.getPoker();
        int playerNum = pokerService.resetPoker(poker);
        NynInfo info = new NynInfo();
        if (poker.substring(1).equals("A")) {
            info.setNeeddrink(infoService.getOne(NynInfo::getPlayerid, playerNum).getNeeddrink() - 1);
            infoService.updateInfo(playerNum, info);
        } else if (usepoker.getPoker().substring(1).equals("2")) {
            return result.error("2不能使用");
        }
        myWebsocket.sendMessageToAllUser();
        return result.success();
    }

    @PostMapping("/drinkData")
    public Result drinkData(drinkData drinkdata) {
        int count = infoService.getInfoCount();
        if (count == 0) {
            return result.error("还未开局，请先完成初始化！");
        }
        int playerNum = drinkdata.getPlayerNum();
        if (playerNum > count || playerNum < 1) {
            return result.error("PlayerNum参数错误");
        }
        NynInfo info = new NynInfo();
        if (drinkdata.getDrinkType() == 1) {
            if (drinkdata.getHasDrinked() == 1) {
                info.setHasdrinked(infoService.getOne(NynInfo::getPlayerid, playerNum).getHasdrinked() + 1);
            } else if (drinkdata.getHasDrinked() == 0) {
                info.setNeeddrink(infoService.getOne(NynInfo::getPlayerid, playerNum).getNeeddrink() + 1);
            } else {
                return result.error("HasDrinked参数错误");
            }
            String i = redisTemplate.opsForValue().get("whohas2");
            if (!StringUtils.isEmpty(i) && Integer.parseInt(i) != playerNum) {
                new NynInfo().setNeeddrink(infoService.getOne(NynInfo::getPlayerid, Integer.parseInt(i)).getNeeddrink() + 1);
            }

        } else if (drinkdata.getDrinkType() == 2) {
            info.setNeeddrink(infoService.getOne(NynInfo::getPlayerid, playerNum).getNeeddrink() - 1);
            info.setHasdrinked(infoService.getOne(NynInfo::getPlayerid, playerNum).getHasdrinked() + 1);
        } else {
            return result.error("drinkType参数错误");
        }
        infoService.updateInfo(playerNum, info);
        myWebsocket.sendMessageToAllUser();
        return result.success();
    }

    @GetMapping("/getPoker")
    public Result getPoker() {
        int count = infoService.getInfoCount();
        if (count == 0) {
            return result.error("还未开局，请先完成初始化！");
        }
        if (pokerService.getPokerCount() > 0) {
            NynInfo infoForDrink = new NynInfo();
            String poker = pokerService.getPoker();
            int whoDrink = 0;
            Integer playerid = Integer.parseInt(redisTemplate.opsForValue().get("now"));
            String i = redisTemplate.opsForValue().get("whohas2");
            if (poker.substring(1).equals("2")) {
                    redisTemplate.opsForValue().set("whohas2", playerid.toString());
            } else {
                if (poker.substring(1).equals("K")) {
                    // 查现在已经出现了几个K
                    int kCount = pokerService.selectKcount();
                    if (kCount != 0) {
                        infoForDrink.setNeeddrink(infoService.getOne(NynInfo::getPlayerid, playerid).getNeeddrink() + kCount);
                    }
                } else {
                    if(poker.substring(1).equals("J")) {
                        whoDrink = playerid == 1 ? count : playerid - 1;
                    } else if (poker.substring(1).equals("Q")) {
                        whoDrink = playerid == count ? 1 : playerid + 1;
                    } else if (poker.substring(1).equals("9")){
                        whoDrink = playerid;
                    }
                    if (whoDrink!=0){
                        infoForDrink.setNeeddrink(infoService.getOne(NynInfo::getPlayerid, whoDrink).getNeeddrink() + 1);
                        infoService.updateInfo(whoDrink, infoForDrink);
                        if (!StringUtils.isEmpty(i) && Integer.parseInt(i) != playerid) {
                            NynInfo sisterDrink = new NynInfo();
                            sisterDrink.setNeeddrink(infoService.getOne(NynInfo::getPlayerid, Integer.parseInt(i)).getNeeddrink() + 1);
                            infoService.updateInfo(Integer.parseInt(i), sisterDrink);
                        }
                    }
                }
            }
            // 更新poker表
            NynPoker poker1 = new NynPoker();
            poker1.setPlayerid(playerid);
            pokerService.updatePoker(poker, poker1);
            // 更新redis
            redisTemplate.opsForValue().set("now", playerid + 1 > count ? "1" : ((Integer) (playerid + 1)).toString());
            redisTemplate.opsForValue().set("lastpoker", poker);
            myWebsocket.sendMessageToAllUser();
            return result.success(poker);
        }
        return result.error("无牌可摸");
    }
}
